#include "graphic_animation_manager.h"
/*--------------------------------------------------------------------------------*/
#include "input_file_manager.h"
#include "input_file.h"
#include "graphic_texture_manager.h"
#include "graphic_texture_set.h"
#include "text.h"
#include "line_parser.h"
/*--------------------------------------------------------------------------------*/
IMPLEMENT_SINGLETON( GRAPHIC_ANIMATION_MANAGER );
/*--------------------------------------------------------------------------------*/
VOID GRAPHIC_ANIMATION_MANAGER::LoadFile( const TEXT & file_name )
{
	INPUT_FILE::REF
		file;
	TEXT
		line,
		animation_name,
		texture_name,
		frames_text;
	REAL
		duration;
	LINE_PARSER
		parser( "*=*;*;*" ),
		atlas_parser( "@*=*x*");

	DEBUG_Log( "Loading animation file \"" + file_name + "\"\n" );

	DEBUG_Require( INPUT_FILE_MANAGER_DoesFileExist( file_name ) );

	file = INPUT_FILE_MANAGER_GetFile( file_name );

	file->Open();

	while( file->ReadLine( line ) )
	{
		if( line[0] != '#' && parser.Parse( line ) )
		{
			GRAPHIC_ANIMATION_DATA::REF
				animation;

			animation_name = parser.GetText( 0 );
			texture_name = parser.GetText( 1 );
			frames_text = parser.GetText( 2 );

			animation_name.RemoveSpaces();
			texture_name.RemoveSpaces();
			frames_text.RemoveSpaces();

			duration = parser.GetReal( 3 );

			animation.New();

			DEBUG_Require( GRAPHIC_TEXTURE_MANAGER_DoesTextureExist( texture_name ) );

			animation->SetTextureSetSource( GRAPHIC_TEXTURE_MANAGER_GetTexture( texture_name ) );
			animation->SetDuration( duration );

			ParseFrames( *animation, frames_text );

			AnimationTable.Add( animation_name, animation );
			DEBUG_Log( "Animation loaded : \"" + animation_name + "\"\n" );
		}
		else if( line[0] != '#' && atlas_parser.Parse( line ) )
		{
			COUNT
				rows,
				columns;

			texture_name = atlas_parser.GetText( 0 );
			texture_name.RemoveSpaces();

			columns = atlas_parser.GetInteger( 1 );
			rows = atlas_parser.GetInteger( 2 );

			if( !GRAPHIC_TEXTURE_MANAGER_DoesTextureExist( texture_name ) )
			{
				GRAPHIC_TEXTURE_MANAGER_AddTexture( texture_name, GRAPHIC_TEXTURE_SET::CreateTextureSetFromFile( texture_name, columns, rows ) );
			}
		}
	}


}
/*--------------------------------------------------------------------------------*/
VOID GRAPHIC_ANIMATION_MANAGER::ParseFrames( GRAPHIC_ANIMATION_DATA & animation, const TEXT & frames_text )
{
	LINE_PARSER
		parser( "*-*" );

	if( parser.Parse( frames_text ) )
	{
		animation.AddFramesInRange( parser.GetInteger( 0 ), parser.GetInteger( 1 ) );
	}
	else
	{
		DEBUG_Break( "Error in animation data syntax." );
	}
}
/*--------------------------------------------------------------------------------*/
